package babo.cd.physicalexperiment.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.alibaba.fastjson.JSON;
import com.aliyun.player.AliPlayer;
import com.aliyun.player.AliPlayerFactory;
import com.aliyun.player.IPlayer;
import com.aliyun.player.bean.ErrorInfo;
import com.aliyun.player.nativeclass.PlayerConfig;
import com.aliyun.player.source.UrlSource;
import com.cicada.player.utils.Logger;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import babo.cd.physicalexperiment.BaseActivity;
import babo.cd.physicalexperiment.R;
import babo.cd.physicalexperiment.app.MyApplication;
import babo.cd.physicalexperiment.bean.MaikerxuntiaojieBean;
import babo.cd.physicalexperiment.data.MyEnventData;
import babo.cd.physicalexperiment.data.RecordData;
import babo.cd.physicalexperiment.data.UserInfo;
import babo.cd.physicalexperiment.databinding.ActivitySettingBinding;
import babo.cd.physicalexperiment.databinding.ActivityYiqijiaozhunBinding;
import babo.cd.physicalexperiment.dialog.TiaozhengmkexDialog;
import babo.cd.physicalexperiment.dialog.YiqiJiaozhunDialog;
import babo.cd.physicalexperiment.utils.Out;
import babo.cd.physicalexperiment.utils.SimpleUtils;
import babo.cd.physicalexperiment.utils.Tool;

import static babo.cd.physicalexperiment.activity.ImagePagerActivity.EXTRA_IMAGE_INDEX;
import static babo.cd.physicalexperiment.activity.ImagePagerActivity.EXTRA_IMAGE_URLS;

public class YiqiJiaozhunActivity extends BaseActivity {
    ActivityYiqijiaozhunBinding binding;

    int flagtz=-1;
    private String ct1="0";
    private String ct2="0";
    private String ct3="0";
    private String ct4="0";
    AliPlayer aliPlayer;
    private String wt1="0";
    private String wt2="0";
    private String wt3="0";
    private String wt4="0";
    YiqiJiaozhunDialog yiqiJiaozhunDialog;
    private String did;
    private String purl;
    private int type=-1;
    File fileStar;

    @Override
    protected View bindView() {
        binding=ActivityYiqijiaozhunBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    protected void initView() {

    }
    private void initWebView() {
        binding.webv.setWebViewClient(new ExampleWebViewClient());
        binding.webv.getSettings().setJavaScriptEnabled(true);
        binding.webv.getSettings().setMediaPlaybackRequiresUserGesture(false);
        binding.webv.getSettings().setLoadWithOverviewMode(true);
        binding.webv.getSettings().setUseWideViewPort(true);

        binding.webv.getSettings().setPluginState(WebSettings.PluginState.ON);
        binding.webv.getSettings().setAllowFileAccess(true);
        binding.webv.getSettings().setSupportZoom(true);
        binding.webv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

        if (Build.VERSION.SDK_INT >= 21) {
            binding.webv.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }


    }

    private void initPlayer() {
        System.loadLibrary("RtsSDK");
        aliPlayer= AliPlayerFactory.createAliPlayer(this);
        PlayerConfig config = aliPlayer.getConfig();
//设置最大延迟为1秒，延迟控制由ARTC控制
        config.mMaxDelayTime = 1000;
//设置播放器启播缓存为10毫秒，数据控制由ARTC控制。
        config.mHighBufferDuration = 10;
        config.mStartBufferDuration = 10;
//其他设置
//给播放器加载配置
        aliPlayer.setConfig(config);
        Logger.getInstance(context).enableConsoleLog(true);
        Logger.getInstance(context).setLogLevel(Logger.LogLevel.AF_LOG_LEVEL_TRACE);

        //     SurfaceHolder holder=   binding.svPlay.getHolder();

//
//        //得到视图的状态
//        holder.addCallback(new SurfaceHolder.Callback() {
//            //视图销毁
//            @Override
//            public void surfaceDestroyed(SurfaceHolder holder) {
//                // TODO Auto-generated method stub
//                aliPlayer.setDisplay(holder);
//            }
//            //视图创建完成
//            @Override
//            public void surfaceCreated(SurfaceHolder holder) {
//                // TODO Auto-generated method stub
//                Out.out("准备好AAA1");
//                aliPlayer.setDisplay(holder);
//                aliPlayer.setSurface(holder.getSurface());
//                aliPlayer.setOnErrorListener(new IPlayer.OnErrorListener() {
//                    @Override
//                    public void onError(ErrorInfo errorInfo) {
//                        //出错事件
//                        Out.out("错粗：="+errorInfo.getMsg());
//                        Out.out("错粗22：="+errorInfo.getExtra());
//                    }
//                });
//        long duration = androidMediaPlayer.getDuration();
//        try {

//                    path="http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8";

//                    UrlSource urlSource=new UrlSource();
//                    urlSource.setUri(playerUrl);
//                    //设置资源
//                    aliPlayer.setDataSource(urlSource);
//                    //异步准备
//                    aliPlayer.prepare();
//                    //播放
//                    aliPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
//                        @Override
//                        public void onPrepared() {
//                            Out.out("视频准备好");
//                            aliPlayer.start();
//                        }
//                    });
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
//            //视图改变
//            @Override
//            public void surfaceChanged(SurfaceHolder holder, int format, int width,
//                                       int height) {
//                aliPlayer.redraw();
//
//            }
//        });
    }
    private void doInitLivePlay() {
        Out.out("开始拉流AAA");

        Logger.getInstance(context).enableConsoleLog(true);
        Logger.getInstance(context).setLogLevel(Logger.LogLevel.AF_LOG_LEVEL_TRACE);
//        EventBus.getDefault().post(MyEnventData.getInstance("startshiyanmkex@"+deviceId));

        SurfaceView surfaceView=new SurfaceView(context);
        binding.llV.addView(surfaceView);
        SurfaceHolder holder=  surfaceView.getHolder();


        //得到视图的状态
        holder.addCallback(new SurfaceHolder.Callback() {
            //视图销毁
            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                // TODO Auto-generated method stub
                aliPlayer.setDisplay(holder);
            }
            //视图创建完成
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                // TODO Auto-generated method stub
                Out.out("准备好AAA1");
                aliPlayer.setDisplay(holder);
                aliPlayer.setSurface(holder.getSurface());
                aliPlayer.setOnErrorListener(new IPlayer.OnErrorListener() {
                    @Override
                    public void onError(ErrorInfo errorInfo) {
                        //出错事件
                        Out.out("错粗：="+errorInfo.getMsg());
                        Out.out("错粗22：="+errorInfo.getExtra());
                    }
                });
//        long duration = androidMediaPlayer.getDuration();
                try {
                    String path="artc://xhapp.cdbfbt.cn/555/555?auth_key=1623554479-0-0-1c73cef9d3744a0db57e143a74151f26";


                    path=purl;
                    Out.out("推流地址=="+path);
//                    path="http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8";

                    UrlSource urlSource=new UrlSource();
                    urlSource.setUri(path);
                    //设置资源
                    aliPlayer.setDataSource(urlSource);
                    //异步准备
                    aliPlayer.prepare();
                    //播放
                    aliPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared() {
                            Out.out("视频准备好");
                            aliPlayer.start();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    Out.out("推流错误=="+e.getMessage());
                }

            }
            //视图改变
            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                       int height) {
                aliPlayer.redraw();

            }
        });



    }
    @Override
    protected void loadData() {
        did=getIntent().getStringExtra("did");
        purl=getIntent().getStringExtra("purl");
        type=getIntent().getIntExtra("type",1);
        initPlayer();
        initWebView();
        if (type==1){
            binding.llV.setVisibility(View.VISIBLE);
            binding.webv.setVisibility(View.GONE);
            doInitLivePlay();
        }else{
            binding.llV.setVisibility(View.GONE);
            binding.webv.setVisibility(View.VISIBLE);
          binding.webv.loadUrl(purl);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void setListener() {
        super.setListener();
        binding.rlDongjingshangxia.setOnClickListener(view -> {
            flagtz=2;
            clearAll();
            binding.rlDongjingshangxia.setBackgroundResource(R.drawable.backbtnblue);
            binding.txDongjingshangxia.setTextColor(Color.parseColor("#ffffff"));
             showTzDialog(flagtz,ct2,wt2);
        });

        binding.rlDongjingzuoyou.setOnClickListener(view -> {
            flagtz=1;
            clearAll();
            binding.rlDongjingzuoyou.setBackgroundResource(R.drawable.backbtnblue);
            binding.txDongjingzuoyou.setTextColor(Color.parseColor("#ffffff"));
            showTzDialog(flagtz,ct1,wt1);

        });
        binding.rlDingjingzuoyou.setOnClickListener(view -> {
            flagtz=3;
            clearAll();
            binding.rlDingjingzuoyou.setBackgroundResource(R.drawable.backbtnblue);
            binding.txDingjingzuoyou.setTextColor(Color.parseColor("#ffffff"));
            showTzDialog(flagtz,ct3,wt3);

        });
        binding.rlDingjingshangxia.setOnClickListener(view -> {
            flagtz=4;
            clearAll();
            binding.rlDingjingshangxia.setBackgroundResource(R.drawable.backbtnblue);
            binding.txDingjingshangxia.setTextColor(Color.parseColor("#ffffff"));
            showTzDialog(flagtz,ct4,wt4);
        });

    }

    private void showTzDialog(int flagtz, String cctt, String wwtt) {
        yiqiJiaozhunDialog=new YiqiJiaozhunDialog(this,flagtz);
        new XPopup.Builder(context)
                .dismissOnTouchOutside(false)
                .asCustom(yiqiJiaozhunDialog)
                .show();

    }

    private void clearAll(){
        binding.rlDingjingshangxia.setBackgroundResource(R.drawable.backbtnbluekong);
        binding.rlDingjingzuoyou.setBackgroundResource(R.drawable.backbtnbluekong);
        binding.rlDongjingshangxia.setBackgroundResource(R.drawable.backbtnbluekong);
        binding.rlDongjingzuoyou.setBackgroundResource(R.drawable.backbtnbluekong);
        binding.txDingjingshangxia.setTextColor(getResources().getColor(R.color.blue));
        binding.txDingjingzuoyou.setTextColor(getResources().getColor(R.color.blue));
        binding.txDongjingshangxia.setTextColor(getResources().getColor(R.color.blue));
        binding.txDongjingzuoyou.setTextColor(getResources().getColor(R.color.blue));
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(MyEnventData message) {
        String msg=message.message;
        if (msg.startsWith("showdongjing@")){
            msg=msg.replace("showdongjing@","");


            final  String mm=msg;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    hd.post(new Runnable() {
                        @Override
                        public void run() {

                            Bitmap bitmap= Tool.stringToBitmap(mm);
                            binding.ivImg.setBackgroundResource(0);
                            try {
                                fileStar= SimpleUtils.save2Album2(context, bitmap);
                                binding.ivImg.setImageURI(Uri.fromFile(fileStar));

                                binding.ivImg.setOnClickListener(v -> {


                                    String [] urls={fileStar.getAbsolutePath()};
                                    Out.out("起点图片=="+fileStar.getAbsolutePath());

                                    Intent intent=new Intent(context,ImagePagerActivity.class);
                                    intent.putExtra(EXTRA_IMAGE_INDEX,0);
                                    intent.putExtra(EXTRA_IMAGE_URLS,urls);
                                    startActivity(intent);
                                });


                            }catch (Exception ex){
                                ex.printStackTrace();
                            }





                        }
                    });

                }
            }).start();








        }
        if (msg.startsWith("yiqijiaozhuna@")){
            Out.out("仪器校准AAAA");
            msg=msg.replace("yiqijiaozhuna@","");
            String[] ss=msg.split("@");
            String ff=ss[0];
            String ct=ss[1];
            Out.out("仪器校准BBB");
            int julict=Integer.parseInt(ct);
//            double zkd=0;
//            zkd=julict*0.01+juliwt*0.0001;
//            double oldkd=0;
//            int type=0;
            if (ff.equals("1")){
                type=5;
//                oldkd=Integer.parseInt(ct1)*0.001+Integer.parseInt(wt1)*0.00001;

            }else if  (ff.equals("2")){
                type=6;
//                oldkd=Integer.parseInt(ct2)*0.001+Integer.parseInt(wt2)*0.00001;
            }else if  (ff.equals("3")){
                type=3;
//                oldkd=Integer.parseInt(ct3)*0.001+Integer.parseInt(wt3)*0.00001;
            }else if  (ff.equals("4")){
                type=4;
//                oldkd=Integer.parseInt(ct4)*0.001+Integer.parseInt(wt4)*0.00001;
            }

            double distance=Double.parseDouble(ct)*0.1;




            MaikerxuntiaojieBean maikerxuntiaojieBean=new MaikerxuntiaojieBean();
            maikerxuntiaojieBean.setAction("adjust");
            maikerxuntiaojieBean.setDevice_id(did);
            maikerxuntiaojieBean.setDistance(distance+"");
            maikerxuntiaojieBean.setExp_id("1");
            maikerxuntiaojieBean.setType(type+"");
            String jg=JSON.toJSONString(maikerxuntiaojieBean);
            Out.out("要发送的校准消息："+jg);
            EventBus.getDefault().post(MyEnventData.getInstance("yiqijiaozhun@"+ jg));



//            if (ff.equals("1")){
//                ct1=ct;
//                wt1=wt;
//            }else if (ff.equals("2")){
//                ct2=ct;
//                wt2=wt;
//            }else if (ff.equals("3")){
//                ct3=ct;
//                wt3=wt;
//            }else if (ff.equals("4")){
//                ct4=ct;
//                wt4=wt;
//            }
//            EventBus.getDefault().post(MyEnventData.getInstance("gundong@"+ct+"@"+wt));
        }


    }

    private class ExampleWebViewClient extends WebViewClient {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }
    }
}
